package com.dragon.shop.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dragon.shop.bean.Order;
import com.dragon.shop.bean.OrderItem;
import com.dragon.shop.bean.Product;
import com.dragon.shop.bean.User;
import com.dragon.shop.order.fegin.ProductService;
import com.dragon.shop.order.fegin.UserService;
import com.dragon.shop.order.mapper.OrderItemMapper;
import com.dragon.shop.order.mapper.OrderMapper;
import com.dragon.shop.order.service.OrderService;
import com.dragon.shop.params.OrderParams;
import com.dragon.shop.utils.constants.HttpCode;
import com.dragon.shop.utils.resp.ResponseEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;

/**
 * @author binghe
 * @version 1.0.0
 * @description
 */
@Slf4j
@Service("orderService")
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {


    private final OrderMapper orderMapper;

    private final OrderItemMapper orderItemMapper;

    private final RestTemplate restTemplate;

    @Resource
    private final UserService userService;
    @Resource
    private final ProductService productService;



    /*@Autowired
    private DiscoveryClient discoveryClient;*/

    //private String userServer = "server-user";

    //private String productServer = "server-product";



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrder(OrderParams orderParams) {
        if (orderParams.isEmpty()){
            throw new RuntimeException("参数异常: " + JSONObject.toJSONString(orderParams));
        }

        /*String userUrl = this.getServiceUrl(userServer);
        String productUrl = this.getServiceUrl(productServer);*/

        //User user = restTemplate.getForObject("http://" + userServer + "/user/get/" + orderParams.getUserId(), User.class);
        User user = userService.getUser(orderParams.getUserId());
        if (user == null){
            throw new RuntimeException("未获取到用户信息: " + JSONObject.toJSONString(orderParams));
        }
        if(user.getId() == -1) {
            throw new RuntimeException("触发了用户微服务的容错逻辑" + JSONObject.toJSONString(orderParams));
        }
        //Product product = restTemplate.getForObject("http://"+ productServer + "/product/get/" + orderParams.getProductId(), Product.class);
        Product product = productService.getProduct(orderParams.getProductId());
        if (product == null){
            throw new RuntimeException("未获取到商品信息: " + JSONObject.toJSONString(orderParams));
        }
        if (product.getId() == -1){
            throw new RuntimeException("触发了商品微服务的容错逻辑: " + JSONObject.toJSONString(orderParams));
        }
        if (product.getProStock() < orderParams.getCount()){
            throw new RuntimeException("商品库存不足: " + JSONObject.toJSONString(orderParams));
        }
        Order order = new Order();
        order.setAddress(user.getAddress());
        order.setPhone(user.getPhone());
        order.setUserId(user.getId());
        order.setUsername(user.getUsername());
        order.setTotalPrice(product.getProPrice().multiply(BigDecimal.valueOf(orderParams.getCount())));
        orderMapper.insert(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setNumber(orderParams.getCount());
        orderItem.setOrderId(order.getId());
        orderItem.setProId(product.getId());
        orderItem.setProName(product.getProName());
        orderItem.setProPrice(product.getProPrice());
        orderItemMapper.insert(orderItem);

        //ResponseEntity result = restTemplate.getForObject("http://"+ productServer + "/product/update_count/" + orderParams.getProductId() + "/" + orderParams.getCount(), ResponseEntity.class);
        ResponseEntity result = productService.updateCount(orderParams.getProductId(), orderParams.getCount());
        if (result.getCode() == 1001){
            throw new RuntimeException("触发了商品微服务的容错逻辑: " + JSONObject.toJSONString(orderParams));
        }
        if (result.getCode() != HttpCode.SUCCESS){
            throw new RuntimeException("库存扣减失败");
        }
        log.info("库存扣减成功");
    }

    /*private String getServiceUrl(String serviceName) {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        int index = new Random().nextInt(instances.size());
        ServiceInstance serviceInstance = instances.get(index);
        String url = serviceInstance.getHost() + ":" + serviceInstance.getPort();
        log.info("负载均衡后的服务地址为:{}", url);
        return url;
    }*/

}
